﻿/*********************************************************************
 * Copyright 2012 Fan Deng.
 * 
 * This file is part of uscis-status-tracker.
 * 
 * uscis-status-tracker is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by 
 * the Free Software Foundation, either version 3 of the License, or 
 * (at your option) any later version.
 * 
 * uscis-status-tracker is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *********************************************************************/

using System;
using System.Text;
using System.Net;
using System.IO;

namespace USCISStatusTracker
{
	[Serializable()]
	class USCISStatus
	{
		private DateTime _timeStamp;
		private string _receiptNumber;
		private string _status;
		private string _details;
		private USCISStatus() { }
		public static USCISStatus Track(string ReceiptNumber)
		{
			StringBuilder sb = new StringBuilder();

			String url = "https://egov.uscis.gov/cris/Dashboard/CaseStatus.do";
			byte[] buf = new byte[8192];
			HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
			StringBuilder postString = new StringBuilder();

			postString.AppendFormat("{0}={1}", "appReceiptNum", System.Web.HttpUtility.UrlEncode(ReceiptNumber));
			ASCIIEncoding ascii = new ASCIIEncoding();
			byte[] postBytes = ascii.GetBytes(postString.ToString());
			request.Method = "POST";
			request.ContentType = "application/x-www-form-urlencoded";
			request.ContentLength = postBytes.Length;

			Stream postStream = request.GetRequestStream();
			postStream.Write(postBytes, 0, postBytes.Length);
			postStream.Close();

			HttpWebResponse response = request.GetResponse() as HttpWebResponse;
			Stream resStream = response.GetResponseStream();

			string tempString = null;
			int count = 0;
			do
			{
				count = resStream.Read(buf, 0, buf.Length);
				if (count != 0)
				{
					tempString = Encoding.UTF8.GetString(buf, 0, count);
					sb.Append(tempString);
				}
			} while (count > 0);

			resStream.Close();

			String content = sb.ToString();
			//Console.WriteLine(content);

			USCISStatus record = new USCISStatus();
			record.ReceiptNumber = ReceiptNumber;
			record.Timestamp = DateTime.Now;
			if (content.Contains("can not be found"))
			{
				record.Status = "Not available";
				record.Details = "Your case can not be found at this time in My Case Status. Please check your receipt number and try again. If you need further assistance, please call the National Customer Service Center at 1.800.375.5283.";
			}
			else if (content.Contains("errorContainer"))
			{
				return null;
			}
			else
			{
				String mark_caseStatusInfo = @"caseStatusInfo";
				int pos = content.IndexOf(mark_caseStatusInfo);
				if (pos != -1)
				{
					//Console.WriteLine("Found");
					content = content.Substring(pos + mark_caseStatusInfo.Length);
					int p1 = content.IndexOf(@"<h4>");
					int p2 = content.IndexOf(@"</h4>");
					//Console.WriteLine("{0} {1}", p1, p2);
					record.Status = content.Substring(p1 + @"<h4>".Length, p2 - @"<h4>".Length - p1);
					record.Status = record.Status.Trim();
					int p3 = content.IndexOf(@"caseStatus") + @"caseStatus"">".Length;
					int p4 = content.IndexOf(@"</p>");
					record.Details = content.Substring(p3, p4 - p3);
					record.Details = record.Details.Trim();
					//Console.WriteLine(record.status);
					//Console.WriteLine(record.detailedStatus);
				}
				//Console.WriteLine("Case status:");
			}
			return record;
		}
		public USCISStatus Refresh()
		{
			USCISStatus newItem = Track(ReceiptNumber);
			if (newItem == null)
			{
				throw new InvalidDataException("Invalid receipt number");
			}
			return newItem;
		}
		public string ReceiptNumber
		{
			get { return _receiptNumber; }
			set { _receiptNumber = value; }
		}
		public string Status
		{
			get { return _status; }
			set { _status = value; }
		}
		public string Details
		{
			get { return _details; }
			set { _details = value; }
		}
		public DateTime Timestamp
		{
			get { return _timeStamp; }
			set { _timeStamp = value; }
		}
	}
}
